<template>
    <div class="task">
        <h3 v-if="type == 'bj' " style="text-align:center;font-weight: 600;margin:10px 0;">采集点维护</h3>
        <h3 v-else style="text-align:center;font-weight: 600;margin:10px 0;">采集点查看</h3>
        <div class="pert">
            <p class="title">采集点列表</p>
            <Row class="box">
                <Col :xs="24">
                    <div class="margin-up-down" v-if="type == 'bj' ">
                        <Button type="info" @click="addLocation" class="addbutton" style="width:51px;height:35px;">
                            <i class = "iconfont icon-add" style="font-size:14px;margin-right:5px"></i>
                        </Button>
                    </div>
                    <div class="margin-up-down">
                        <Input class="w-input" v-model="searchKey" clearable placeholder="采集点名称"/>
                    </div>
                    <div class="margin-up-down">
                        <Button type="primary" @click="loadPage(1)" style="width:51px;height:35px;">
                            <Icon type="ios-search" size="14"/>
                        </Button>
                    </div>
                    <div class="margin-up-down">
                        <Button @click="cancel" class="btn">
                            <i class = "iconfont icon-gengxin" style="font-size:14px;margin-right:5px"></i>
                        </Button>
                    </div>
                </Col>
            </Row>
            <Table class="box" v-if="type == 'bj'" border stripe :columns="locationColumn" :data="locationlist"></Table>
            <Table class="box" v-else border stripe :columns="locationColumnCK" :data="locationlist"></Table>
            <div class="page">
                <Page :total="count" :current='pageNo' :page-size="pageSize" show-total show-elevator @on-change="loadPage"/>
            </div>
            <div class="btnBox">
                <Button @click="goback" class="btn">
                    <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>返回
                </Button>
            </div>
        </div>
        <Modal
			v-model="locationModal"
            :title = "locationTitle"
			:footer="null"
            :mask-closable="false"
            :width = '450'
            styles="padding: none;margin: none"
            class="addoredit"
        >
        <!-- 控制弹窗右上角x号是否显示 :closable="false" -->
            <Form ref="locationform" :model="locationform" :rules="locationRules" :label-width="100" label-position="left" style="margin:0 25px">
                <FormItem prop="locationId" label='选择采集点：'>
                    <Select class="w-select" clearable filterable v-model="locationform.locationId" placeholder="请选择采集点" @on-change="changelocation">
						<Option v-for="(item,index) in datalist" :key='index' :value="item.id">{{item.locationName}}</Option>
					</Select>
                </FormItem>
                <!-- <br /> -->
				<FormItem label='采集地点：'>
                    <span>{{locationform.address}}</span>
                </FormItem>
                <!-- <br /> -->
                <FormItem label='联系人：'>
                   <Select class="w-select" clearable filterable v-model="locationform.contactId" placeholder="请选择联系人"  @on-change="chooseContact" label-in-value='true'>
						<Option v-for="(item,index) in contactlist" :key="index" :value="item.id">
							{{item.name}}&nbsp;&nbsp;&nbsp;&nbsp;{{item.phone}}
						</Option>
					</Select>
                </FormItem>
                <!-- <br /> -->
				<FormItem label='联系电话：'>
                    <span>{{locationform.contactPhone}}</span>
                </FormItem>
                <!-- <br />        -->
                <FormItem prop="workerNum" label='计划工作人数（人）：' :label-width="150">
                    <InputNumber class="w-inputNumber" v-if="mode !== 'review'" v-model="locationform.workerNum" placeholder="请输入计划工作人数" :min='1'></InputNumber>
                </FormItem>
                <FormItem prop="outsideNum" label='计划定点检测人数（人）：' :label-width="170">
                    <InputNumber class="w-inputNumber" v-if="mode !== 'review'" v-model="locationform.outsideNum" placeholder="请输入计划定点检测人数" :min='1'></InputNumber>
                </FormItem>
				<FormItem prop="roomNum" label='计划上门检测人数（人）：' :label-width="170">
                    <InputNumber class="w-inputNumber" v-if="mode !== 'review'" v-model="locationform.roomNum" placeholder="请输入计划上门检测人数" :min='1'></InputNumber>
                </FormItem>
				<FormItem prop="workHour" >
                    <!-- label='预估工时（小时）：' :label-width="130" -->
                    <div style='display:flex;margin-left:-100px'>
                        <span style='color:#fc6c49;font-size:18px;margin-right:5px'>*</span><span >预估工时（小时）：</span>
                        <input min="0" max="24" v-if="mode !== 'review'" v-model="locationform.workHours" type="number" @input="srInput" placeholder="请输入数字" class="inputnumber" />
                    </div>
                </FormItem>
                <FormItem >
                    <div style='display:flex;margin-left:-100px'>
                        <span style='color:#fc6c49;font-size:18px;margin-right:5px'>*</span><span >采集时间：</span>
                        <TimePicker v-if="mode !== 'review'" format="HH:mm" type="timerange" placement="bottom-end" v-model="locationform.collectTime" placeholder="请选择采集时间" :steps="[1, 10]" :disabled-hours="disabledHours" hide-disabled-options style="width: 168px;margin-left:15px"></TimePicker>
                    </div>
                </FormItem>
            </Form>
            <div slot="footer" class="btn-group" style="text-align:center">
                <Button type="primary" @click="submitLocation('locationform')" style="width:75px;height:35px;" :disabled='disabledSave'>
                    <Icon type="ios-checkmark" style="margin-right: 5px" />保存
                </Button>
                <Button @click="closelocationModal" style="width:75px;height:35px;">
                    <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
                </Button>
            </div>
		</Modal>
        <Modal
			v-model="delModal"
            title = "删除任务"
			:footer="null"
            :mask-closable="false"
            :width = '450'
            styles="padding: none;margin: none"
        >
        <!-- 控制弹窗右上角x号是否显示 :closable="false" -->
            <div class="box">
                确定要删除此采集点吗？删除后不可恢复！
            </div>
            <div slot="footer" class="btn-group" style="text-align:center">
                <Button type="primary" @click="deltask" style="width:75px;height:35px;" :disabled='disabledDel'>
                    <Icon type="ios-checkmark" style="margin-right: 5px" />确定
                </Button>
                <Button @click="delModal = false" style="width:75px;height:35px;">
                    <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
                </Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import api from "@/api/commonApi";
import { TimePicker } from "view-design";
export default {
    components: {
		TimePicker,
	},
    data() {
		return {
            locationModal: false,
            delid: '',
			locationform: {
                locationId: '',
                locationName: '',
                contactId: '',
                contactName: '',
                contactPhone: '',
                workerNum: '',
                outsideNum: '',
                roomNum: '',
                workHour: '',
                workHours: '',
                taskId: this.id,
                longitude: '',
                latitude: '',
                locationCode: '',
                collectTime: [],
      		},
			locationRules: {
				locationId: [{ required: true, message: "请选择采集点", trigger: "blur" }],
                workerNum: [{ required: true, message: "请输入计划工作人数", trigger: "blur",type:'number' }],
				outsideNum: [{ required: true, message: "请输入计划定点检测人数", trigger: "blur" ,type:'number'}],
				roomNum: [{ required: true, message: "请输入计划上门检测人数", trigger: "blur", type:'number' }],
				// workHour: [{ required: true, message: "请输入预估工时", trigger: "blur", type:'number' }],
			},
            locationColumn: [
				{ title: "排序", key: "iNum", align: "center", width: 70,
                    render: (h, params) => {
                        let iNum = (this.pageNo-1)*this.pageSize + params.index +1;
                        return h("span", iNum);
                    }
                },
                {
                    title: "采集点",
                    key: "locationName",
                    align: "center",
                    // width: 300
                },
                {
                    title: "采集地点",
                    key: "address",
                    align: "center",
                    // width: 300
                },
                {
                    title: "联系人",
                    key: "contactName",
                    align: "center",
                    width: 100,
                },
				{
                    title: "联系电话",
                    key: "contactPhone",
                    align: "center",
                    width: 100,
                },
				{
                    title: "计划工作人数（人）",
                    key: "workerNum",
                    align: "center",
                    width: 100,
                },
				{
                    title: "计划定点检测人数（人）",
                    key: "outsideNum",
                    align: "center",
                    width: 100,
                },
				{
                    title: "计划上门检测人数（人）",
                    key: "roomNum",
                    align: "center",
                    width: 100,
                },
				{
                    title: "预估工时（小时）",
                    key: "workHour",
                    align: "center",
                    width: 100,
                    render: (h, params) => {
                        let workHour = params.row.workHour/60;
                        return h("span", {
                            domProps: {
                                innerHTML: workHour
                            }
                        });
                    }
                },
                {
                    title: "设置",
                    key: "operate",
                    align: "center",
                    width: 110,
                    render: (h, params) => {
                        let id = params.row.id;
                        return [
                            h(
                                "span",
                                {
                                    attrs: {
                                        href: "javascript:void(0);"
                                    },
                                    style: {
                                        color: '#5362e1',
                                        margin: "0px 6px"
                                    },
                                    on: {
                                        click: () => {
                                            this.locationModal = true,
                                            this.locationTitle = '编辑采集点'
                                            this.getlocationlist()
                                            this.getContactlist()
                                            this.findTaskLocationDetails(id)
                                        }
                                    }
                                },
                                "编辑"
                            ),
                            h(
                                "span",
                                {
                                    attrs: {
                                        href: "javascript:void(0);"
                                    },
                                    style: {
                                        color: '#fc6c49',
                                        margin: "0px 6px"
                                    },
                                    on: {
                                        click: () => {
                                            this.delid = id
                                            this.delModal = true
                                        }
                                    }
                                },
                                "删除"
                            ),
                        ];
                    }
                }
			],
            locationColumnCK: [
                { title: "排序", key: "iNum", align: "center", width: 100,
                    render: (h, params) => {
                        let iNum = (this.pageNo-1)*this.pageSize + params.index +1;
                        return h("span", iNum);
                    }
                },
                {
                    title: "采集点",
                    key: "locationName",
                    align: "center",
                    // width: 300
                },
                {
                    title: "采集地点",
                    key: "address",
                    align: "center",
                    // width: 300
                },
                {
                    title: "联系人",
                    key: "contactName",
                    align: "center",
                    width: 100,
                },
				{
                    title: "联系电话",
                    key: "contactPhone",
                    align: "center",
                    width: 100,
                },
				{
                    title: "计划工作人数（人）",
                    key: "workerNum",
                    align: "center",
                    width: 100,
                },
				{
                    title: "计划定点检测人数（人）",
                    key: "outsideNum",
                    align: "center",
                    width: 100,
                },
				{
                    title: "计划上门检测人数（人）",
                    key: "roomNum",
                    align: "center",
                    width: 100,
                },
				{
                    title: "预估工时（小时）",
                    key: "workHour",
                    align: "center",
                    width: 100,
                    render: (h, params) => {
                        let workHour = params.row.workHour/60;
                        return h("span", {
                            domProps: {
                                innerHTML: workHour
                            }
                        });
                    }
                },
            ],
			locationlist: [],
			datalist: [],
            count: 0,
            pageSize: 10,
            pageNo: 1,
            id: null,
            locationTitle: '添加采集点',
            contactlist: [],
            disabledSave: false,
            searchKey: '',
            planeBeginTime: '',
            planeEndTime: '',
            planedata: '',
            type: 'bj',
            delModal: false,
            disabledDel: false,
            disabledHours: [],
        }
    },
    created() {
        this.id = this.$route.query.id ? this.$route.query.id : null;
        this.type = this.$route.query.type ? this.$route.query.type : null;
		let breadList = [
		{ path: "/index", title: "首页" },
		{
			path: "/index/publicOperation/healthInformation/list",
			title: "健康资讯管理"
		}
		];
		this.$emit("changeBreadList", breadList);
	},
	mounted() {
        this.id = this.$route.query.id ? this.$route.query.id : null;
        this.planeBeginTime = this.$route.query.planeBeginTime ? this.$route.query.planeBeginTime : null;
        this.planeEndTime = this.$route.query.planeEndTime ? this.$route.query.planeEndTime : null;
        this.planedata = this.$route.query.planedata ? this.$route.query.planedata : null;
        if(this.planeBeginTime&&this.planeEndTime) {
            this.locationform.collectTime = [this.planeBeginTime,this.planeEndTime]
        }
        this.loadPage(1)
        this.getCurrentTimeDisabled()
	},
	methods: {
        // 根据任务采集时间限制显示此处可见的采集时间段
        getCurrentTimeDisabled(){
            this.disabledHours = []
            let startHour = Number(this.planeBeginTime.substring(0,2))
            let endHour = Number(this.planeEndTime.substring(0,2))
            for(let i=0; i<startHour;i++) {
                this.disabledHours.push(i)
            }
            for(let x=(endHour+1); 24>x;x++) {
                this.disabledHours.push(x)
            }
        },
        goback() {
            this.functionJS.queryNavgationTo(
                this,
                "/index/nucleicacid/task/list",
                {
                    pageNo: 1,
                }
            );
        },
        //加载列表数据
        loadPage(pageNo) {
            this.pageNo = parseInt(pageNo);
            var params = {};
            params.searchKey = this.searchKey.trim();
            params.taskId = this.id;
            params.pageNo = pageNo;
            params.pageSize = this.pageSize;
            this.$axios
                .post(api.findTaskLocationList, params)
                .then(resp => {
                    if (resp.data.success) {
                        this.count = resp.data.object.total;
                        if(resp.data.object.records) {
                            this.locationlist = resp.data.object.records;
                        } else {
                            this.locationlist = []
                            this.count = 0
                        }
                    } else {
                        this.$Message.info("不允许访问");
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        cancel() {
            this.searchKey = ''
            this.loadPage(1)
        },
		//添加采集点
		addLocation() {
			this.locationModal = true
            this.getlocationlist()
            this.getContactlist()
		},
        closelocationModal() {
            this.locationform = {
                locationId: '',
                locationName: '',
                contactId: '',
                contactName: '',
                contactPhone: '',
                workerNum: '',
                outsideNum: '',
                roomNum: '',
                workHour: '',
                workHours: '',
                taskId: this.id,
                longitude: '',
                latitude: '',
                locationCode: '',
                collectTime: [this.planeBeginTime,this.planeEndTime]
      		},
            this.locationModal = false
        },
        //获取采集点列表
        getlocationlist() {
            var params = {};
            params.searchStatus = 1;
            params.pageNo = 1;
            params.pageSize = 10000;
            this.$axios
                .post(api.findLocationPage, params)
                .then(resp => {
                    if (resp.data.success) {
                        if(resp.data.object.records) {
                            this.datalist = resp.data.object.records;
                        } else {
                            this.datalist = []
                        }
                    } else {
                        this.$Message.info("不允许访问");
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        changelocation() {
            this.datalist.forEach(i =>{
                if(this.locationform.locationId == i.id) {
                    this.locationform.address = i.address
                    this.locationform.locationName = i.locationName
                    this.locationform.longitude = i.longitude
                    this.locationform.latitude = i.latitude
                    this.locationform.locationCode = i.locationCode
                }
            })
        },
        //获取所有联系人
        getContactlist() {
            var params = {};
            params.searchStatus = 1;
            params.pageNo = 1;
            params.pageSize = 100000;
            this.$axios
                .post(api.findContactPage, params)
                .then(resp => {
                    if (resp.data.success) {
                        if(resp.data.object.records) {
                            this.contactlist = resp.data.object.records;
                        } else {
                            this.contactlist = []
                        }
                    } else {
                        this.$Message.info("不允许访问");
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
		chooseContact(e) {
			this.contactlist.forEach(i => {
				if(i.id == this.locationform.contactId) {
                    this.locationform.contactName = i.name
                    this.locationform.contactPhone = i.phone
				}
			})
            if(this.locationform.contactId == undefined) {
                this.locationform.contactId = ''
                this.locationform.contactPhone = ''
                this.locationform.contactName = ''
            }
		},
        submitLocation() {
            if(!this.locationform.workHours) {
				this.$Message.error("请完整填写预估工时!");
				return;
			}
            if(!this.locationform.collectTime[0]) {
				this.$Message.error("请完整填写采集时间!");
				return;
			}
            if(this.locationform.collectTime[1]>this.planeEndTime) {
                this.$Message.error("采集截止时间不可超过" + this.planeEndTime);
				return;
            }
            this.disabledSave = true
            this.$refs['locationform'].validate(valid => {
                if (valid) {
                    this.locationform.workHour = this.locationform.workHours*60
                    this.locationform.planeBeginTime = this.planedata + ' ' + this.locationform.collectTime[0] + ':00';
					this.locationform.planeEndTime = this.planedata + ' ' + this.locationform.collectTime[1] + ':00';
                    this.locationform.taskId = this.id
                    this.$axios.post(api.saveTaskLocationDetails, this.locationform).then(res => {
						if (res.data.success) {
							this.$Message.success(res.data.message);
							this.disabledSave = false
                            this.closelocationModal()
                            this.loadPage(1)
						} else {
							this.$Message.error(res.data.message);
							this.disabledSave = false
						}
					}).catch(() => {
						this.disabledSave = false
					});
                } else {
					this.$Message.error("请完整填写必填项!");
					this.disabledSave = false
				}
            });
        },
        findTaskLocationDetails(id) {
			this.$axios.post(api.findTaskLocationDetails, {id}).then(res => {
				if (res.data.success) {
					this.locationform = res.data.object;
                    this.locationform.workHours = this.locationform.workHour/60
                    this.locationform.collectTime = [this.locationform.planeBeginTime.substring(11,16),this.locationform.planeEndTime.substring(11,16)]
				} else {
					this.$Message.error(res.data.message);
				}
			}).catch(() => {
                this.$Message.error(res.data.message);
			});
		},
        deltask() {
            this.disabledDel = true
            let id = this.delid
            this.$axios.post(api.deleteTaskLocationDetails, {id}).then(res => {
                if (res.data.success) {
                    this.$Message.success(res.data.message);
                    this.disabledDel = false
                    this.delModal = false
                    this.loadPage(1)
                } else {
                    this.$Message.error(res.data.message);
                    this.disabledDel = false
                }
            }).catch(() => {
                this.disabledDel = false
            });
        },
        srInput(e) {
			this.locationform.workHours = e.target.value.match(/^\d*(\.?\d{0,2})/g)[0] || null;
          	if(e.target.value>24)this.locationform.workHours=24
		},
    },
}
</script>

<style scoped lang="less">
.task {
	width: calc(100%);
	padding: 10px 0px;
	margin: 0 auto;
	background: #fff;
	.tit {
		margin:10px 0;
		font-weight:bold;
		text-align:center;
	}
    .margin-up-down {
        display: inline-block;
        margin: 10px 0;
    }
    .w-input {
        width: 200px;
    }
    .pert {
		width: 98%;
		display: flex;
		flex-direction: column;
		margin: 10px auto;
		border: 1px solid #f0f0f0;
		box-shadow: 0 4px 3px #ebedf8;
		border-radius: 5px;
		margin-bottom: 20px;
		.title {
			font-size: 20px;
			padding-left: 15px;
			margin-bottom: 10px;
			color: #333;
			height: 40px;
			line-height: 40px;
			background: #ebedf8;
    	}
        .box{
			margin: 0 15px;
		}
        .page {
            text-align: center;
            margin: 15px 0;
        }
    }
	.btnBox {
		width: 100%;
		text-align: center;
        margin-bottom: 20px;
		.btn {
			width: 75px;
			height: 35px;
		}
	}
	.icon {
		font-size:14px;
		margin-right:5px;
	}
}
.w-inputNumber {
    width: 200px;
}
.inputnumber {
    width: 150px;
    background: #fff;
    border: none;
    outline: none;
    text-indent: 10px;
    line-height: 30px;
    border: 1px solid #ddd;
    border-radius: 4px;
    color: #666;
    margin-left:15px;
}
.inputnumber:focus{
    border-color:#5362e1;
}
.addoredit{
    /deep/ .ivu-modal-wrap {
        .ivu-modal{
            float:right !important;
            background-color: #fff;
            border-radius: 10px;
            top: 0px;
            height: 100%;
        }
    }
}
</style>